package org.vidi.springamqp.producer;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.vidi.springamqp.entity.Order;

/**
 * @author vidi
 */
@Component
public class OrderProducerConfirm {
    private final RabbitTemplate rabbitTemplate;

    private final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
        if (ack) {
            // When check ack successful, do some execution here.
            System.out.println("Check successful.");
            System.out.println("Order Message Id: " + correlationData.getId());
        } else {
            // When check ack failed, do some execution here.
            System.err.println(cause);
        }
    };

    public OrderProducerConfirm(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void send(Order order) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(order.getMessageId());
        rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "order.2", order, correlationData);
    }
}
